import React, { useState, useEffect } from 'react'
import { Card, Row, Col, Statistic, List, Typography, Tag, Spin } from 'antd'
import { 
  DesktopOutlined, 
  CheckCircleOutlined, 
  CloseCircleOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons'
import { useAuth } from '../contexts/AuthContext'
import { deviceAPI, systemAPI } from '../services/api'

const { Title } = Typography

const Dashboard = () => {
  const { user } = useAuth()
  const [stats, setStats] = useState({
    totalDevices: 0,
    onlineDevices: 0,
    offlineDevices: 0,
    errorDevices: 0
  })
  const [recentDevices, setRecentDevices] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetchDashboardData()
  }, [])

  const fetchDashboardData = async () => {
    try {
      setLoading(true)
      
      // 获取设备列表
      const devicesResponse = await deviceAPI.getDevices({ page_size: 100 })
      const devices = devicesResponse.data?.devices || []
      
      // 计算统计信息
      const totalDevices = devices.length
      const onlineDevices = devices.filter(d => d.status === 'online').length
      const offlineDevices = devices.filter(d => d.status === 'offline').length
      const errorDevices = devices.filter(d => d.status === 'error').length
      
      setStats({
        totalDevices,
        onlineDevices,
        offlineDevices,
        errorDevices
      })
      
      // 获取最近更新的设备
      const sortedDevices = [...devices]
        .sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
        .slice(0, 5)
      
      setRecentDevices(sortedDevices)
      
    } catch (error) {
      console.error('获取仪表板数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const getStatusIcon = (status) => {
    switch (status) {
      case 'online':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />
      case 'offline':
        return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />
      case 'error':
        return <ExclamationCircleOutlined style={{ color: '#faad14' }} />
      default:
        return <CloseCircleOutlined style={{ color: '#d9d9d9' }} />
    }
  }

  const getStatusTag = (status) => {
    const statusConfig = {
      online: { color: 'success', text: '在线' },
      offline: { color: 'error', text: '离线' },
      error: { color: 'warning', text: '错误' }
    }
    
    const config = statusConfig[status] || { color: 'default', text: status }
    return <Tag color={config.color}>{config.text}</Tag>
  }

  if (loading) {
    return (
      <div style={{ padding: '50px', textAlign: 'center' }}>
        <Spin size="large" />
      </div>
    )
  }

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <Title level={2}>仪表板</Title>
        <p>欢迎回来, {user?.username}!</p>
      </div>

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总设备数"
              value={stats.totalDevices}
              prefix={<DesktopOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="在线设备"
              value={stats.onlineDevices}
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="离线设备"
              value={stats.offlineDevices}
              valueStyle={{ color: '#ff4d4f' }}
              prefix={<CloseCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="异常设备"
              value={stats.errorDevices}
              valueStyle={{ color: '#faad14' }}
              prefix={<ExclamationCircleOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={16}>
        {/* 最近设备 */}
        <Col span={12}>
          <Card title="最近更新的设备" bordered={false}>
            <List
              dataSource={recentDevices}
              renderItem={(device) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={getStatusIcon(device.status)}
                    title={device.name}
                    description={
                      <div>
                        <div>设备ID: {device.device_id}</div>
                        <div>类型: {device.device_type === 'direct' ? '直连设备' : '网关设备'}</div>
                        <div>最后更新: {new Date(device.updated_at).toLocaleString()}</div>
                        {getStatusTag(device.status)}
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>

        {/* 系统信息 */}
        <Col span={12}>
          <Card title="系统信息" bordered={false}>
            <List>
              <List.Item>
                <List.Item.Meta
                  title="平台版本"
                  description="Things IoT Platform v1.0.0"
                />
              </List.Item>
              <List.Item>
                <List.Item.Meta
                  title="用户角色"
                  description={user?.role === 'super_admin' ? '超级管理员' : '普通用户'}
                />
              </List.Item>
              <List.Item>
                <List.Item.Meta
                  title="登录时间"
                  description={new Date().toLocaleString()}
                />
              </List.Item>
            </List>
          </Card>
        </Col>
      </Row>
    </div>
  )
}

export default Dashboard